package com.example.controller;

/**
 * @author 吕一明
 * @公众号 码客在线
 */

import cn.hutool.http.HttpUtil;
import org.redisson.api.RLock;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Controller
public class IndexController extends BaseController {

    @RequestMapping({"", "/", "/index"})
    public String index () {
        req.setAttribute("base", req.getContextPath());
        return "index";
    }

    @ResponseBody
    @GetMapping("/getLastRank")
    public Object getLastRank() {
        Set<ZSetOperations.TypedTuple> lastWeekRank = redisUtil.getZSetRank("last_week_rank", 0, 9);

        List<Map<String, Object>> hotPosts = new ArrayList<>();
        for (ZSetOperations.TypedTuple typedTuple : lastWeekRank) {

            Map<String, Object> map = new HashMap<>();
            map.put("comment_count", typedTuple.getScore());
            map.put("id", redisUtil.hget("rank_post_" + typedTuple.getValue(), "post:id"));
            map.put("title", redisUtil.hget("rank_post_" + typedTuple.getValue(), "post:title"));

            hotPosts.add(map);
        }
        return hotPosts;
    }

    @ResponseBody
    @GetMapping("/post/{id}")
    public Object view(@PathVariable Long id) {
        return postService.get(id);
    }

    @ResponseBody
    @GetMapping("/post/update/{id}")
    public Object update(@PathVariable Long id) {
        return postService.update(postService.get(id));
    }


    @ResponseBody
    @GetMapping("/count")
    public void count() {
        RLock lock = redissonClient.getLock("countincr");
        lock.lock();

        try {

            Integer count = (Integer) redisUtil.get("count");
            if(count == null) {
                count = 0;
            }
            redisUtil.set("count", count + 1);

            System.out.println( Thread.currentThread().getId() + " ---------- " + count);
        } finally {

            lock.unlock();
        }
    }

    @ResponseBody
    @GetMapping("/test")
    public void test() {
        HttpUtil.createGet("http://localhost:8080/count");
        HttpUtil.createGet("http://localhost:8081/count");
    }
}
